﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBMan.Common.Global;
using DBMan.Common.Helper;
using DBMan.Common.Helper.Mqtt;
using DBMan.Common.Helper.Udp;
using Newtonsoft.Json;

namespace DBMan.Receive
{
    public class Deal
    {
        private const string LOG_ERR_FILE = "LogErr.txt";
        private const string LOG_TRACE_FILE = "LogTrace.txt";

        public readonly static Deal Instance = new Deal();

        /// <summary>
        /// 接收数据的方式 0:Udp 1:Mqtt
        /// </summary>
        public int DataReceiveType { get; set; } = 0;

        /// <summary>
        /// Udp广播数据接收端口
        /// </summary>
        public int UdpPort { get; set; } = 9895;

        /// <summary>
        /// Mqtt处理对像
        /// </summary>
        private MQTTHelper mQTTHelper = null;

        private bool IsUdpStart = false;
        /// <summary>
        /// Mqtt连接配置Json字符串 { serverAddr,iPort,user,pwd }
        /// </summary>
        public string MqttConnectJsonStr { get; set; } = "";

        private List<string> _MqttSubscribeList = new List<string>() { "DBManSyncOperDataDataPublish" };
        /// <summary>
        /// Mqtt订阅主题列表
        /// </summary>
        public List<string> MqttSubscribeList
        {
            get
            {
                return _MqttSubscribeList;
            }
        }

        private Deal()
        {
            try
            {
                if (int.TryParse(Configs.GetAndAdd("DataReceiveType", "0"), out var i))
                {
                    this.DataReceiveType = i;
                }
                var defaultJson = JsonConvert.SerializeObject(new
                {
                    serverAddr = "121.136.140.57",
                    iPort = 1883,
                    user = "w.f",
                    pwd = "123"
                });
                var jsonTag = "'";
                defaultJson = defaultJson.Replace("\"", jsonTag);
                var json = Configs.GetAndAdd("DataReceiveMqttConnectJsonStr", defaultJson);
                json = json.Replace(jsonTag, "\"");
                this.MqttConnectJsonStr = json;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Err:{ex.Message}");
            }
        }

        public void Start()
        {
            try
            {
                switch (this.DataReceiveType)
                {
                    case 0:
                        if (this.IsUdpStart)
                        {
                            break;
                        }
                        this.IsUdpStart = true;
                        UdpHelper.ReceiveStart(this.UdpPort);
                        UdpHelper.ReceiveEvnt += ((ob) =>
                        {
                            try
                            {
                                var _json = (string)ob;
                                //json = $"\r\n{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\r\n接收到的Udp广播数据:\r\n{Tool.ConvertJsonString(json)}\r\n";
                                //Console.WriteLine(json);                               
                                this.DataReceiveEventDeal(_json);
                            }
                            catch (Exception ex)
                            {
                                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Start 0Err:{ex.Message}");
                            }
                        });
                        break;
                    case 1:
                        if (this.mQTTHelper != null)
                        {
                            return;
                        }
                        this.mQTTHelper = MQTTHelper.Instance;
                        var json = this.MqttConnectJsonStr;
                        var cfg = Tool.ToDynamicsByJson(json).Select(p => new
                        {
                            serverAddr = p.Get<string>("serverAddr"),
                            iPort = p.Get<int>("iPort"),
                            user = p.Get<string>("user"),
                            pwd = p.Get<string>("pwd")
                        }).First();
                        this.mQTTHelper.Connect(/*"121.136.140.57"*/cfg.serverAddr, /*1883*/cfg.iPort, /*"w.f"*/cfg.user, /*"123"*/cfg.pwd);
                        this.mQTTHelper.MQTTConnectedEvent += ((s, e) =>
                        {
                            try
                            {
                                var sLog = $"\r\nMqtt连接成功!\r\n{Tool.ConvertJsonString(json)}\r\n";
                                Console.WriteLine(sLog);
                                //mQTTHelper.Publish("a/b/c", $"nkdWuFeng:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
                                LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);

                                //this.TestMqttSubscribe();
                                this.MqttSubscribeDeal();
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine($"MQTTConnectedEvent Err:{ex.Message}");
                                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Start MQTTConnectedEvent Err:{ex.Message}");
                            }
                        });
                        this.mQTTHelper.MQTTReConnectedFailEvent += ((s, e) =>
                        {
                            try
                            {
                                //Console.WriteLine("Mqtt重连失败!");
                                var sLog = $"\r\nMqtt重连失败!\r\n{Tool.ConvertJsonString(json)}\r\n";
                                Console.WriteLine(sLog);
                                LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine($"MQTTReConnectedFailEvent Err:{ex.Message}");
                                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Start MQTTReConnectedFailEvent Err:{ex.Message}");
                            }
                        });
                        this.mQTTHelper.MQTTReceivedDataEvent += ((s, e) =>
                        {
                            try
                            {
                                var mrdm = (MQTTReceivedDataModel)s;
                                //var obLog = new
                                //{
                                //    mrdm.Topic,
                                //    mrdm.Payload
                                //};
                                //var sLog = $"\r\n{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\r\n接收到的Mqtt订阅数据:\r\n{Tool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(obLog))}\r\n";
                                //Console.WriteLine(sLog);                               
                                this.DataReceiveEventDeal(mrdm.Payload);
                            }
                            catch (Exception ex)
                            {
                                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Start MQTTReceivedDataEvent Err:{ex.Message}");
                            }
                        });
                        break;
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal Start Err:{ex.Message}");
            }
        }

        private void MqttSubscribeDeal()
        {
            try
            {
                var msl = this.MqttSubscribeList;
                foreach (var s in msl)
                {
                    this.mQTTHelper.Subscribe(s);
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal MqttSubscribeDeal Err:{ex.Message}");
            }
        }

        private void DataReceiveEventDeal(string _json)
        {
            try
            {
                var th = new System.Threading.Thread((ob) =>
                {
                    try
                    {
                        var json = (string)ob;
                        //...Todo... 二次开发在此增补代码                        
                        var sLog = $@"
【描述】= 接收到数据推手推送过来的数据
【数据】=
{Tool.ConvertJsonString(json)}
";
                        LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);
                        Test.Instance.TestDeal(json);
                    }
                    catch (Exception ex)
                    {
                        LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal DataReceiveEventDeal 0Err:{ex.Message}");
                    }
                });
                th.Start(_json);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Receive Deal DataReceiveEventDeal Err:{ex.Message}");
            }
        }

    }
}
